package cn.ncu.wechat.controller;

import cn.ncu.wechat.service.OrdersService;
import cn.ncu.wechat.service.ProductService;
import cn.ncu.wechat.util.Result;
import cn.ncu.wechat.vo.OrderVo;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;


@RestController
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ProductService productService;
    @PostMapping("/api/wx/orders")
    public Result<?> AddOrder(@RequestBody OrderVo orderVo, @RequestHeader("Authorization") Optional<String> authorizationHeader){
        int check = 500;
        check = ordersService.checkOrder(orderVo);
        if(check==404){
            return Result.error(404,"商品不存在");
        }
        else if(check==400){
            return Result.error(400,"参数错误，下单量应大于0");
        }
        else return ordersService.AddOrder(orderVo,authorizationHeader.get());
    }

    @GetMapping("/api/wx/orders")
    public Result<?> getOrderList(@RequestParam  Integer page,@RequestParam Integer pageSize,@RequestParam Integer status){
        if(page<=0||page==null||pageSize<=0||pageSize==null||status<0||status>4){
            page = 1;
            pageSize = 10;
            status = 0;
        }
        return ordersService.getOrdersByKey(page,pageSize,status);
    }

    @GetMapping("/api/wx/orders/{orderNo}")
    public Result<?> getOrderDetail(@PathVariable String orderNo){
        return ordersService.getOrderDetail(orderNo);
    }

    @GetMapping("/api/admin/orders")
    public Result<?> getOrderListByKey(@RequestParam  Integer page,@RequestParam Integer pageSize,@RequestParam Integer status,@RequestParam String orderNo,@RequestParam String phone){
        return ordersService.getOrderListByKey(page,pageSize,status,orderNo,phone);
    }
    @GetMapping("/api/wx/orders/{orderNo}/pay")
    public Result<?> payOrder(@PathVariable String orderNo){
        return ordersService.payOrder(orderNo);
    }

    @PostMapping("/api/wx/orders/{ordersNo}/refund")
    public Result<?> refundOrder(@PathVariable String ordersNo,@RequestBody String reason){
        return ordersService.refundOrder(ordersNo,reason);
    }
}
